<template>
  <d2-container>
    <template slot="header">敞口管理-新增</template>
    <el-card shadow="never" class="d2-mb titleline">
      <template slot="header" style="height:66px;">
        <span class="title_x el-button--primary fl"></span>
        <p class="title_l fl">主要信息</p>
      </template>
      <el-form class="filter-container" ref="ckxhForm" :rules="rules" :model="ckxhForm" label-width="110px">
        <el-row :gutter="20">
          <el-col :span="4">
            <el-form-item label="部门名称" prop="department">
              <el-select v-model="ckxhForm.department" placeholder="请选择" style="width:100%;">
                <el-option v-for="item in selectDepartsList" :key="item.department" :label="item.name"
                  :value="item.department">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="客户名称" prop="customer">
              <el-select v-model="ckxhForm.customer" placeholder="请选择" style="width:100%;">
                <el-option v-for="item in customerList" :key="item.customer" :label="item.name" :value="item.customer">
                  <span style="float: left">{{item.name}}</span>
                  <!-- <span style="float: right; color: #8492a6; font-size: 13px">{{ item.customer}}</span> -->
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="币种" prop="currency">
              <el-select v-model="ckxhForm.currency" placeholder="请选择" style="width:100%;">
                <el-option v-for="item in selectCurrencyList" :key="item.currency" :label="item.name"
                  :value="item.currency">
                  <span style="float: left">{{item.name}}</span>
                  <!-- <span style="float: right; color: #8492a6; font-size: 13px">{{ item.currency}}</span> -->
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="方向" prop="direction">
              <el-select clearable v-model="ckxhForm.direction" class="filter-item" placeholder="请选择">
                <el-option label="采购" value="0"></el-option>
                <el-option label="销售" value="1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="4">
            <el-form-item label="定价方式">
              <el-select  clearable v-model="ckxhForm.pricing_method" clearable class="filter-item" placeholder="请选择" @change="show_AccountName">
              <el-option label="一口价" value="0"></el-option>
              <el-option label="点价" value="1"></el-option>
              <el-option label="均价" value="2"></el-option>
            </el-select>
            </el-form-item>
          </el-col> -->
          <el-col :span="4">
            <el-form-item label="虚拟购销" prop="virtual">
              <el-select clearable v-model="ckxhForm.virtual" class="filter-item" placeholder="请选择">
                <el-option label="是" value="1"></el-option>
                <el-option label="否" value="0"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="期初标识" prop="begin_flag">
              <el-select clearable v-model="ckxhForm.begin_flag" class="filter-item" placeholder="请选择">
                <el-option label="是" value="1"></el-option>
                <el-option label="否" value="0"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <el-card shadow="never" class="d2-mb titleline">
      <template slot="header" style="height:66px;">
        <span class="title_x el-button--primary fl"></span>
        <p class="title_l fl">详细信息</p>
      </template>
      <!-- <el-card shadow="never" class="d2-mb"> -->
      <div class="tl mb10">
        <el-button type="default" size="mini" @click="addRow">
          <d2-icon name="plus" />
          增行
        </el-button>
        <el-button type="default" size="mini" icon="el-icon-delete" @click="delData">
          删行
        </el-button>
        <!-- <el-button type="default" size="mini" @click="handleFilter_countCkgl">
          <i class="fa fa-building-o" aria-hidden="true"></i>
          计算
        </el-button> -->
      </div>
      <el-form label-position="right" status-icon :rules="rules" :model="ckxhtableData" ref="ruleForm">
        <el-table :data="ckxhtableData" ref="table" tooltip-effect="dark" border stripe style="width: 100%"
          :row-class-name="tableRow" :cell-style="{ 'text-align': 'center' }"
          :header-cell-style="{ 'text-align': 'center' }" @selection-change='selectRow' highlight-current-row>
          <el-table-column type="selection" width="40" align="center"></el-table-column>
          <el-table-column label="序号" type="index" width="55" align="center"></el-table-column>
          <el-table-column label="敞口类型" align="center" width="110">
            <template slot-scope="scope">
              <el-select clearable v-model="scope.row.exp_type" placeholder="请选择" filterable allow-create>
                <el-option label="逐笔" value="0"></el-option>
                <el-option label="净敞口" value="1"></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="定价方式" align="center" width="110">
            <template slot-scope="scope">
              <el-select clearable v-model="scope.row.pricing_method" placeholder="请选择" filterable allow-create
                @input="BGX">
                <el-option label="一口价" value="0"></el-option>
                <el-option label="点价" value="1"></el-option>
                <el-option label="均价" value="2"></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="合同号" align="center" width="110">
            <template slot-scope="scope">
              <el-form-item :prop="scope.$index + '.deal_no'" :rules="rules.deal_no">
                <el-input class="deal_no" v-model="scope.row.deal_no"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <!-- <el-table-column  label="敞口号" align="center">
                <template slot-scope="scope">
                  <el-input class="exposure_no" v-model="scope.row.exposure_no"></el-input>
                </template>
              </el-table-column> -->
          <el-table-column label="品名" width="145">
            <template slot-scope="scope">
              <div>
                <el-form-item class="id dib" :prop="scope.$index + '.commodity'" :rules="rules.commodity"
                  style="width:60px;margin-right:5px;">
                  <el-input class="id dib" v-model="scope.row.commodity_name" style="width:60px;margin-right:5px;"
                    disabled></el-input>
                  <el-input class="id dib" v-model="scope.row.commodity" style="width:60px;margin-right:5px;" v-if="a">
                  </el-input>
                </el-form-item>
                <el-button type="primary" size="mini" plain @click="PMdialog(scope.$index,scope.row)">选择</el-button>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="仓库" align="center" width="110">
            <template slot-scope="scope">
              <el-form-item :prop="scope.$index + '.depot'" :rules="rules.depot">
                <el-input class="depot" v-model="scope.row.depot"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="单据数量" align="center" width="110">
            <template slot-scope="scope">
              <el-form-item :prop="scope.$index + '.invoice_vol'" :rules="rules.invoice_vol">
                <el-input v-model="scope.row.invoice_vol" type="number" min="1"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="敞口数量" align="center" width="110">
            <template slot-scope="scope">
              <el-form-item :prop="scope.$index + '.exp_vol'" :rules="rules.exp_vol">
                <el-input v-model="scope.row.exp_vol" type="number" :readonly="scope.row.pricing_method != '1'">
                </el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="定价开始日期" width="160" class="date" sortable>
            <template slot-scope="scope">
              <el-form-item :prop="scope.$index + '.start_date'" :rules="rules.start_date">
                <el-date-picker v-model="scope.row.start_date" v-show="scope.row.pricing_method == '0'"
                  :picker-options="pickerOptions" type="date" value-format="yyyy-MM-dd" placeholder="选择日期"
                  style="width:100%;padding-right:0;"></el-date-picker>
                <el-date-picker v-model="scope.row.start_date"
                  v-show="scope.row.pricing_method == '1'||scope.row.pricing_method == '2'" type="date"
                  value-format="yyyy-MM-dd" placeholder="选择日期" style="width:100%;padding-right:0;"></el-date-picker>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="基准价格" align="center" width="170">
            <template slot-scope="scope">
              <div>
                <el-form-item class="id dib" :prop="scope.$index + '.base_price'" :rules="rules.base_price">
                  <el-input class="id dib" v-model="scope.row.base_price_name" style="width:88px;margin-right:5px;"
                    disabled></el-input>
                  <el-input class="id dib" v-model="scope.row.base_price" style="width:88px;margin-right:5px;" v-if="a">
                  </el-input>
                </el-form-item>
                <el-button type="primary" size="mini" plain @click="DJdialog(scope.$index,scope.row)">选择</el-button>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="汇率" align="center" width="90">
            <template slot-scope="scope">
              <el-form-item :prop="scope.$index + '.exchange_rate'" :rules="rules.exchange_rate">
                <el-input v-model="scope.row.exchange_rate" type="number"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="单价" align="center" width="90">
            <template slot-scope="scope">
              <el-input v-model="scope.row.unit_price" type="number" :readonly="scope.row.pricing_method == '2'">
              </el-input>
            </template>
          </el-table-column>
          <el-table-column label="升贴水" align="center" width="90">
            <template slot-scope="scope">
              <el-input v-model="scope.row.bwd" type="number"
                :readonly="scope.row.pricing_method == '0' || scope.row.pricing_method == '2'"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="价格" align="center" width="90">
            <template slot-scope="scope">
              <el-input v-model="scope.row.price" type="number" disabled></el-input>
            </template>
          </el-table-column>
          <el-table-column label="本币价格" align="center" width="90">
            <template slot-scope="scope">
              <el-input v-model="scope.row.currency_price" type="number" disabled></el-input>
            </template>
          </el-table-column>
          <el-table-column label="件数" align="center" width="90">
            <template slot-scope="scope">
              <el-form-item :prop="scope.$index + '.piece_num'" :rules="rules.piece_num">
                <el-input v-model="scope.row.piece_num" type="number"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="每件数量" align="center" width="90">
            <template slot-scope="scope">
              <el-input v-model="scope.row.piece_vol" type="number" :prop="scope.$index + '.piece_vol'"
                :rules="rules.piece_vol"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="定价结束日期" width="160" sortable>
            <template slot-scope="scope">
              <el-form-item :prop="scope.$index + '.end_date'" :rules="rules.end_date">
                <el-date-picker v-model="scope.row.start_date" v-if="scope.row.pricing_method == '0'" type="date"
                  value-format="yyyy-MM-dd" :readonly="scope.row.pricing_method == '0'" placeholder="选择日期"
                  style="width:100%;padding-right:0;"></el-date-picker>
                <!-- <el-date-picker v-model="scope.row.end_date" type="date" value-format="yyyy-MM-dd" :readonly="scope.row.pricing_method == '0'" placeholder="选择日期" style="width:100%;padding-right:0;"></el-date-picker> -->
                <el-date-picker v-model="scope.row.end_date" v-else
                  v-show="scope.row.pricing_method == '1'||scope.row.pricing_method == '2'" type="date"
                  value-format="yyyy-MM-dd" placeholder="选择日期" style="width:100%;padding-right:0;"></el-date-picker>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="备注" align="center">
            <template slot-scope="scope">
              <el-input class="remark" v-model="scope.row.remark"></el-input>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
    </el-card>
    <el-button type="primary" size="mini" style="float:right;margin-left: 10px;"
      @click="CkglChange('ckxhForm','ruleForm')">计算并保存</el-button>
    <!-- <el-button type="default" size="mini" style="float:right">取消</el-button> -->
    <!-- 品名 -->
    <el-dialog :visible.sync="PMdialogVisible" title="品名" width="74%">
      <el-table :data="PMNameList" border highlight-current-row @current-change="handleCurrentChange_ta">
        <el-table-column type="index" label="序号"></el-table-column>
        <el-table-column prop="status" label="状态" sortable :formatter="PMStatus"></el-table-column>
        <el-table-column prop="category" label="品类" sortable></el-table-column>
        <el-table-column prop="commodity" label="品名" sortable></el-table-column>
        <el-table-column prop="id" label="品名ID" sortable></el-table-column>
        <el-table-column prop="commodity_unit" label="商品单位" sortable :formatter="SPFormat"></el-table-column>
        <el-table-column prop="measure_unit" label="计量单位" sortable :formatter="JLFormat"></el-table-column>
        <el-table-column prop="tax_typeName" label="税种" sortable></el-table-column>
        <el-table-column prop="start_date" label="开始日期" sortable></el-table-column>
        <el-table-column prop="rate" label="税率" sortable></el-table-column>
        <el-table-column prop="brand" label="品牌" sortable></el-table-column>
        <el-table-column prop="origin" label="产地" sortable></el-table-column>
        <el-table-column prop="standard" label="规格" sortable></el-table-column>
        <el-table-column prop="attribute" label="主属性" sortable></el-table-column>
        <el-table-column prop="desc" label="备注" sortable></el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="PMdialogVisible = false">取消</el-button>
        <el-button type="primary" @click="PMIDChange">保存</el-button>
      </div>
    </el-dialog>
    <!-- 基准价格 -->
    <el-dialog :visible.sync="DjjzdialogVisible" title="价格项-基准价格" width="74%">
      <el-table :data="GzjzNameList" border highlight-current-row @current-change="handleCurrentChange_ta">
        <el-table-column type="index" label="序号"></el-table-column>
        <el-table-column prop="status" label="状态" sortable :formatter="formatterStatus"></el-table-column>
        <el-table-column prop="id" label="价格项ID" sortable></el-table-column>
        <el-table-column prop="name" label="价格项名称" sortable></el-table-column>
        <el-table-column prop="price_origin" label="价格项来源" sortable :formatter="price_originFormat"></el-table-column>
        <el-table-column prop="price_unit_name" label="单位" sortable :formatter="DWFormat"></el-table-column>
        <el-table-column prop="price_formula" label="定价公式" sortable></el-table-column>
        <el-table-column prop="desc" label="备注" sortable></el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="DjjzdialogVisible = false">取消</el-button>
        <el-button type="primary" @click="DjjzChange">保存</el-button>
      </div>
    </el-dialog>

  </d2-container>
</template>

<script>
  import {
    concustomer,
    addExposure,
    conCommodity,
    conPriceitem,
    conCurrency,
    calculate
  } from '../../../../../api/url_lcc';
  import {
    getDepartments
  } from '../../../../../api/url';
  export default {
    //现货期货套期-新增/编辑
    name: "add_open",
    //   components: {
    //     "trade-name": tradeName
    //   },
    data() {
      return {
        a: false,
        customerList: [],
        selectDepartsList: [],
        ckxhtableData: [{
          exp_type: '1',
          pricing_method: '0',
          deal_no: '',
          // exposure_no:'',
          commodity: '',
          depot: '',
          invoice_vol: '',
          exp_vol: '',
          start_date: '',
          base_price: '',
          base_valuation: '',
          exchange_rate: '',
          unit_price: '',
          bwd: '0',
          price: '',
          currency_price: '',
          piece_num: '',
          piece_vol: '',
          end_date: '',
          // require_des: '',
          // post_id: '',
          remark: ''
        }],
        selectCurrencyList: [],
        currentRow: {},
        ckxhForm: {
          "department": "",
          "customer": "",
          "currency": "",
          "direction": "1",
          "virtual": "1",
          "begin_flag": "1",
        },
        ruleForm: {
          "deal_no": "",
          "commodity": "",
          "depot": "",
          "invoice_vol": "",
          "exp_vol": "",
          "start_date": "",
          "base_price": "",
          "base_valuation": "",
          "exchange_rate": "",
          "unit_price": "",
          "bwd": "",
          "price": "",
          "currency_price": "",
          "piece_num": "",
          "piece_vol": "",
          "end_date": "",
          "direction": "",
          "virtual": "",
          "begin_flag": "",
          //            "remark": ""
        },
        PMNameList: [],
        selectlistRow: [],
        rowNum: 1,
        PMdialogVisible: false,
        DjjzdialogVisible: false,
        GzjzdialogVisible: false,
        row: "",
        // ///////////////////////////////时间限制
        pickerOptions: {
          disabledDate(time) {
            return time.getTime() > Date.now(); //选择时间范围
          }
        },
        // disabledDate:time =>{
        // let DateVal = this.ckxhtableData[0].start_date;
        // if (DateVal) {
        //   return time.getTime() < Date.now();
        // }
        // }
        //  },
        pickerOptionsStart: {
          disabledDate: time => {
            let endDateVal = this.CKForm.endDate;
            if (endDateVal) {
              return time.getTime() > new Date(endDateVal).getTime();
            }
          }
        },
        pickerOptionsEnd: {
          disabledDate: time => {
            let beginDateVal = this.CKForm.startDate;
            if (beginDateVal) {
              return (
                time.getTime() <
                new Date(beginDateVal).getTime() - 1 * 24 * 60 * 60 * 1000
              );
            }
          }
        },
        rules: {
          department: [{
            required: true,
            message: '请选择部门名称',
            trigger: 'change'
          }],
          customer: [{
            required: true,
            message: '请选择客户名称',
            trigger: 'change'
          }],
          currency: [{
            required: true,
            message: '请选择币种',
            trigger: 'change'
          }],
          deal_no: [{
            required: true,
            message: '请输入合同号',
            trigger: 'blur'
          }, ],
          commodity: [{
            required: true,
            message: '请选择品名',
            trigger: 'blur'
          }, ],
          base_price: [{
            required: true,
            message: '请选择基准价格',
            trigger: 'blur'
          }, ],
          depot: [{
            required: true,
            message: '请输入仓库',
            trigger: 'blur'
          }, ],
          invoice_vol: [{
            required: true,
            message: '请输入单据数量',
            trigger: 'blur'
          }, ],
          start_date: [{
            type: 'string',
            required: true,
            message: '请选择定价开始日期',
            trigger: 'change'
          }],
          exchange_rate: [{
            required: true,
            message: '请输入汇率',
            trigger: 'blur'
          }, ],
          //  piece_num: [
          //   { required: true, message: '请输入件数', trigger: 'blur' },
          // ],
          //  piece_vol: [
          //   { required: true, message: '请输入每件数量', trigger: 'blur' },
          // ],
          direction: [{
            required: true,
            message: '请选择方向',
            trigger: 'blur'
          }, ],
          virtual: [{
            required: true,
            message: '请选择虚拟购销',
            trigger: 'blur'
          }, ],
          begin_flag: [{
            required: true,
            message: '请选择期初标识',
            trigger: 'blur'
          }, ]
          //  remark: [
          //   { required: true, message: '请输入备注', trigger: 'blur' },
          // ],
        },
        cusForm: {
          name: "",
          type: "",
          status: "",
          black: "",
        },
      };
    },
    created() {
      this.tabledatas.map(i => {
        i.show = false
        return i
      })
    },
    filters: {

    },
    methods: {
      // ////////////////////////////////////////////////////////////敞口管理
      // 品名
      PMStatus(row, column) {
        return row.status == "0" ? '不可用' : '可用'
      },
      // 单位
      SPFormat(row, column) {
        if (row.commodity_unit == "0") {
          return '吨';
        } else if (row.commodity_unit == "1") {
          return '千克';
        } else if (row.commodity_unit == "2") {
          return '桶';
        } else if (row.commodity_unit == "3") {
          return '立方米';
        } else if (row.commodity_unit == "4") {
          return '张';
        } else if (row.commodity_unit == "5") {
          return '克';
        }
      },
      JLFormat(row, column) {
        if (row.measure_unit == "0") {
          return '吨';
        } else if (row.measure_unit == "1") {
          return '千克';
        } else if (row.measure_unit == "2") {
          return '桶';
        } else if (row.measure_unit == "3") {
          return '立方米';
        } else if (row.measure_unit == "4") {
          return '张';
        } else if (row.measure_unit == "5") {
          return '克';
        }
      },
      // 价格项
      formatterStatus(row, column) {
        return row.status == "0" ? '停用' : '启用'
      },
      price_originFormat(row, column) {
        if (row.price_origin == "0") {
          return '现货行情';
        } else if (row.price_origin == "1") {
          return '期货主力合约行情';
        } else if (row.price_origin == "2") {
          return '期货合约行情';
        } else if (row.price_origin == "3") {
          return '计算项';
        } else if (row.price_origin == "4") {
          return '用户现货行情';
        }
      },
      DWFormat(row, column) {
        if (row.price_unit === 0) {
          return '吨';
        } else if (row.price_unit === 1) {
          return '千克';
        } else if (row.price_unit === 2) {
          return '桶';
        } else if (row.price_unit === 3) {
          return '立方米';
        } else if (row.price_unit === 4) {
          return '张';
        } else if (row.price_unit === 5) {
          return '克';
        }
      },
      //  部门信息
      //树形结构转换为扁平数组
      treeToList(tree) {
        var queen = [];
        var out = [];
        queen = queen.concat(tree);
        while (queen.length) {
          var first = queen.shift();
          if (first.sub_depart) {
            queen = queen.concat(first.sub_depart);
            delete first["sub_depart"];
          }
          out.push(first);
        }
        return out;
      },
      // 查询部门
      handle_getDepartments() {
        getDepartments()
          .then(res => {
            this.selectDepartsList = [];
            var data1 = res.result;
            var arr = this.treeToList(data1);
            for (var i = 0; i < arr.length; i++) {
              this.selectDepartsList[i] = {
                name: arr[i]["name"],
                department: arr[i]["id"]
              };
            }
          })
          .catch(err => {
            this.$message.error(err.msg);
          });
      },
      //  客商信息
      handle_customerChange() {
        concustomer(this.cusForm).then(res => {
          this.customerList = []
          var data = res.result
          for (var i = 0; i < data.length; i++) {
            this.customerList[i] = {
              'customer': data[i].id,
              'name': data[i].name
            }
          }
          console.log(1, data, 2, this.customerList)
        }).catch(err => {
          this.$message.error(err.msg);
        });
      },
      // 行内编辑
      handleCellDataChange({
        rowIndex,
        key,
        value,
        row
      }) {
        debbuger;
        console.log(rowIndex);
        console.log(key);
        console.log(value);
        console.log(row);
      },
      // 单选
      handleCurrentChange(currentRow, oldCurrentRow) {
        console.log(currentRow);
        console.log(oldCurrentRow);
      },
      handleCurrentChange_ta(val) {
        this.currentRow = val;
        console.log('估值', this.currentRow)
      },
      // 多选
      handleSelectionChange(selection) {
        console.log(selection);
      },
      // 获取表格选中时的数据
      selectRow(val) {
        this.selectlistRow = val
      },
      // 增加行
      addRow() {
        var list = {
          rowNum: this.rowNum,
          exp_type: '1',
          pricing_method: '0',
        };
        this.ckxhtableData.unshift(list)
        this.rowNum += 1;
      },
      // 删除方法
      // 删除选中行
      delData() {
        for (let i = 0; i < this.selectlistRow.length; i++) {
          let val = this.selectlistRow
          val.forEach((val, index) => {
            this.ckxhtableData.forEach((v, i) => {
              if (val.rowNum === v.rowNum) {
                // i 为选中的索引
                this.ckxhtableData.splice(i, 1)
              }
            })
          })
        }
        // 删除完数据之后清除勾选框
        this.$refs.table.clearSelection()
      },
      // 品名
      PMNameChange() {
        let params = {
          "category": "",
          "name": "",
          "commodity_spot__brand": "",
          "status": "",
        };
        conCommodity(params).then(res => {
          this.$message.success(res.result);
          this.PMNameList = []
          var data = res.result
          for (var i = 0; i < data.length; i++) {
            this.PMNameList[i] = {
              'status': data[i].tax_type['status'],
              'category': data[i]['category'],
              'commodity': data[i]['name'],
              'id': data[i]['id'],
              'commodity_unit': data[i]['commodity_unit'],
              'measure_unit': data[i]['measure_unit'],
              'tax_typeName': data[i].tax_type['name'],
              'start_date': data[i].tax_type['start_date'],
              'rate': data[i].tax_type['rate'],
              'brand': data[i].commodity_spot[0]['brand'],
              'origin': data[i].commodity_spot[0]['origin'],
              'standard': data[i].commodity_spot[0]['standard'],
              'attribute': data[i].commodity_spot[0]['attribute'],
              'desc': data[i]['desc']
            }
          }
        }).catch(err => {
          this.$message.error(err.msg);
        });
      },
      // 品名弹框
      PMdialog(index, row) {
        this.PMdialogVisible = true
        this.PMNameChange();
        this.index_s = index
      },
      // 品名保存
      PMIDChange(index) {
        this.PMdialogVisible = false
        console.log('品名保存', this.currentRow, 1, this.index_s)
        this.ckxhtableData[this.index_s].commodity = this.currentRow.id
        this.ckxhtableData[this.index_s].commodity_name = this.currentRow.commodity
        console.log(142, this.ckxhtableData[this.index_s].commodity_name)
      },
      // 估值基准
      GzjzNameChange() {
        let params = {
          "name": "",
          "status": "",
          "price_origin": ""
        };
        conPriceitem(params).then(res => {
          this.$message.success(res.result);
          this.GzjzNameList = []
          var data = res.result
          for (var i = 0; i < data.length; i++) {
            this.GzjzNameList[i] = {
              'status': data[i]['status'],
              'id': data[i]['id'],
              'name': data[i]['name'],
              "price_origin": data[i]['price_origin'],
              "price_unit": data[i]['price_unit'],
              "price_unit_name": data[i]['price_unit_name'],
              "price_formula": data[i]['price_formula'],
              "desc": data[i]['desc']
            }
          }
        }).catch(err => {
          this.$message.error(err.msg);
        });
      },

      // 定价弹框
      DJdialog(index, row) {
        this.DjjzdialogVisible = true
        this.GzjzNameChange();
        this.index_s = index
      },
      // 定价保存
      DjjzChange(index) {
        this.DjjzdialogVisible = false
        console.log('估值保存', this.currentRow, 1, this.index_s)
        this.ckxhtableData[this.index_s].base_price = this.currentRow.id
        this.ckxhtableData[this.index_s].base_price_name = this.currentRow.name
        console.log(142, this.ckxhtableData[this.index_s].base_price_name)
      },
      // 查询币种
      handle_currencyChange() {
        let params = {
          "name": "",
        };
        conCurrency(params).then(res => {
          this.selectCurrencyList = []
          var data1 = res.result
          console.log(902, )
          for (var i = 0; i < data1.length; i++) {
            this.selectCurrencyList[i] = {
              currency: data1[i]['id'],
              name: data1[i]['name']
            };
          }
        }).catch(err => {
          this.$message.error(err.msg);
        });
      },
      // 计算
      handleFilter_countCkgl() {
        var data = this.selectlistRow
        console.log(121, this.selectlistRow.length)
        if (this.selectlistRow.length == 0) {
          this.openMessage();
        } else {
          this.count_msg()
        }
      },
      count() {
        console.log('计算所需数据', this.selectlistRow)
        let params = {
          operation: 'EXP',
          exp: this.selectlistRow
        };
        calculate(params).then(res => {
          this.$message.success(res.result);
          this.ckxhtableData = []
          var data1 = res.result
          for (var i = 0; i < data1.length; i++) {
            this.ckxhtableData[i] = {
              "pricing_method": data1[i].pricing_method,
              "exp_type": data1[i].exp_type,
              "deal_no": data1[i].deal_no,
              "commodity": data1[i].commodity,
              "depot": data1[i].depot,
              "invoice_vol": data1[i].invoice_vol,
              "exp_vol": data1[i].new_exp_vol,
              "start_date": data1[i].start_date,
              "base_price": data1[i].base_price,
              "base_valuation": data1[i].base_valuation,
              "exchange_rate": data1[i].exchange_rate,
              "unit_price": data1[i].unit_price,
              "bwd": data1[i].bwd || "0",
              "price": data1[i].new_price,
              "currency_price": data1[i].new_currency_price,
              "piece_num": data1[i].piece_num,
              "piece_vol": data1[i].piece_vol,
              "end_date": data1[i].end_date,
              "remark": data1[i].remark,
            }
          }
          console.log('新数据', this.ckxhtableData)
        }).catch(err => {
          this.$message.error(err.msg);
        });
      },
      count_msg() {
        this.$confirm('是否计算价格及敞口数量?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.count()
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消计算'
          });
        });
      },
      // 多选提示
      openMessage() {
        this.$message({
          dangerouslyUseHTMLString: true,
          type: 'error',
          message: '<strong>请勾选你要选择的行，再进行操作！</strong>'
        });
      },
      // 新增-敞口管理
      CkglChange(ckxhForm, ruleForm) {
        console.log('查看数据', this.ckxhtableData)
        this.ckxhtableData.forEach(item => {
          console.log(90,item.pricing_method != '0',0,item.end_date == '');
          if(item.pricing_method == '0'){
            item.end_date = item.start_date
          }else if(item.pricing_method != '0' && item.end_date == ''){
             this.$message.error('定价结束日期不能为空，请输入定价结束日期！')
          }else{
            item.end_date = item.end_date
          }
        });
        const rule1 = new Promise((resolve, reject) => {
          this.$refs[ckxhForm].validate(valid => {
            if (valid) {
              resolve();
            } else {
              console.log("error submit!!");
              return false;
            }
          });
        });
        const rule2 = new Promise((resolve, reject) => {
          this.$refs[ruleForm].validate(valid => {
            if (valid) {
              resolve();
            } else {
              console.log("error submit!!");
              return false;
            }
          });
        });
        Promise.all([rule1, rule2]).then(() => {
          let params = {
            operation: 'EXP',
            exp: this.ckxhtableData
          };
          calculate(params).then(res => {
            this.$message.success(res.result);
            this.ckxhtableData = []
            var data1 = res.result
            for (var i = 0; i < data1.length; i++) {
              this.ckxhtableData[i] = {
                "pricing_method": data1[i].pricing_method,
                "exp_type": data1[i].exp_type,
                "deal_no": data1[i].deal_no,
                "commodity": data1[i].commodity,
                "depot": data1[i].depot,
                "invoice_vol": data1[i].invoice_vol,
                "exp_vol": data1[i].new_exp_vol,
                "start_date": data1[i].start_date,
                "base_price": data1[i].base_price,
                "base_valuation": data1[i].base_valuation,
                "exchange_rate": data1[i].exchange_rate || "0",
                "unit_price": data1[i].unit_price || "0",
                "bwd": data1[i].bwd || "0",
                "price": data1[i].new_price || "0",
                "currency_price": data1[i].new_currency_price || "0",
                "piece_num": data1[i].piece_num || "0",
                "piece_vol": data1[i].piece_vol || "0",
                "end_date": data1[i].end_date,
                "remark": data1[i].remark,
              }
            }
            this.add_ckList();
          }).catch(err => {
            this.$message.error(err.msg);
          });
        });
      },
      add_ckList(ckxhForm, ruleForm) {
         this.ckxhtableData.forEach(item => {
          console.log(90,item.pricing_method != '0',0,item.end_date == '');
          if(item.pricing_method == '0'){
            item.end_date = item.start_date
          }else if(item.pricing_method != '0' && item.end_date == ''){
             this.$message.error('定价结束日期不能为空，请输入定价结束日期！')
          }else{
            item.end_date = item.end_date
          }
        });
        let params = {
          operation: "ADD",
          "main": {
            "department": this.ckxhForm.department,
            "customer": this.ckxhForm.customer,
            "currency": this.ckxhForm.currency,
            "direction": this.ckxhForm.direction,
            "pricing_method": this.ckxhForm.pricing_method,
            "virtual": this.ckxhForm.virtual,
            "begin_flag": this.ckxhForm.begin_flag,
          },
          "spot_exposure": this.ckxhtableData
        };
        addExposure(params).then(res => {
          this.$message.success(res.result);
          this.$router.push({
            path: '/arbitrage_tool/cash_management'
          });
          this.closeing.closePage(this.$store.getters["d2admin/page/allPage"], this.$store.getters[
            "d2admin/page/currentPage"])
        }).catch(err => {
          this.$message.error(err.msg);
        });
        // });
      }
    },
    mounted() {
      this.handle_currencyChange();
      this.GzjzNameChange();
      this.handle_customerChange();
      this.handle_getDepartments();
    }
  };

</script>
<style lang="scss">
  .el-form-item {
    margin-bottom: 0px !important;
  }

</style>
